import type { ClearingPriceForecast } from './type';
import _ from 'lodash';
import { export_json_to_excel } from '@/utils/fileExport';
import { message } from 'antd';

export const transformResDataToTableData = (data: ClearingPriceForecast[]) => {
  const columns: any = [
    {
      code: 'type',
      title: '类型',
      lock: true,
      align: 'left',
      width: 120,
    },
    ...(data?.map((item) => ({
      code: item.forecastTime,
      title: item.forecastTime.substring(0, 8) + ' ' + item.forecastTime.substring(8),
      width: 130,
      align: 'center',
      render: (v: number) => v ?? '-',
    })) || []),
  ];
  const dayAheadClearingPriceForecast: Record<string, number | string> = { type: '日前电价预测' };
  const realTimeClearingPriceForecast: Record<string, number | string> = { type: '实时电价预测' };

  data?.forEach((item) => {
    dayAheadClearingPriceForecast[item.forecastTime] = item.dayAheadClearingPriceForecast;
    realTimeClearingPriceForecast[item.forecastTime] = item.realTimeClearingPriceForecast;
  });

  return {
    columns,
    dataSource: [dayAheadClearingPriceForecast, realTimeClearingPriceForecast],
  };
};

export const transformResDataToChartData = (data: ClearingPriceForecast[]) => {
  return {
    xisx:
      data?.map((item) => {
        return item.forecastTime.substring(0, 8) + ' ' + item.forecastTime.substring(8);
      }) || [],
    dayAheadClearingPriceForecast: data?.map((item) => item?.dayAheadClearingPriceForecast) || [],
    realTimeClearingPriceForecast: data?.map((item) => item?.realTimeClearingPriceForecast) || [],
  };
};

export const exportTableData = (data: {
  columns: any;
  dataSource: Record<string, string | number>[];
}) => {
  if (_.isEmpty(data?.dataSource)) {
    message.error('暂无可导出数据，请查询后重试');
    return;
  }

  // 构建表头
  const header = data.columns.map((col: any) => col.title);

  // 构建数据行
  const excelData = data.dataSource.map((row: any) =>
    data.columns.map((col: any) => row[col.code] || ''),
  );

  export_json_to_excel({
    header,
    data: excelData,
    filename: `电价预测`,
    autoWidth: true,
  });
};
